<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home/prolist' }">项目列表</el-breadcrumb-item>
        <el-breadcrumb-item>项目立项</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 立项信息 -->
        <div class="card-title">立项信息</div>
        <el-form label-width="100px" :model="creatPro" :rules="creatProRules" ref="creatPro">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item style="margin:0" label="标记转签">
                  <el-radio-group v-model="creatPro.sign" @change="isSigned">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item style="margin:0" label="接收转签">
                <el-radio-group v-model="creatPro.receive" @change="isRelated">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
              </el-form-item>
            </el-col>
             <el-col :span="8" v-if="isRelat">
               <!-- 关联项目 -->
              <el-form-item style="margin:0" label="关联项目" prop="related" :rules="[{ required: true, message: '选择关联项目', trigger: 'change' }]">
                <el-select style="width:100%" v-model="creatPro.related">
                  <el-option v-for="sign in signList" :key="sign.id" :label="sign.proName" :value="sign.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
           <el-divider></el-divider>
          <el-row :gutter="24">
            <el-col :span="8">
              <!-- 公司 -->
              <el-form-item label="归属公司" prop="compId">
                <el-select style="width:100%" v-model="creatPro.compId">
                  <el-option v-for="item in compList" :key="item.id" :label="item.compName" :value="item.compId"></el-option>
                </el-select>
              </el-form-item>
              <!-- 项目类型 -->
              <el-form-item label="项目类型" prop="type">
                <el-select style="width:100%" v-model="creatPro.type">
                  <el-option label="销售类项目" value="XS"></el-option>
                  <el-option label="研发类项目" value="YF"></el-option>
                </el-select>
              </el-form-item>
              <!-- 客户名称 -->
              <el-form-item label="客户名称" prop="cusId">
                <el-select style="width:100%" clearable filterable v-model="creatPro.cusId">
                  <el-option v-for="key in cusList" :key="key.id" :label="key.cusName" :value="key.id"></el-option>
                </el-select>
              </el-form-item>
              <!-- 合同编号 -->
              <el-form-item label="合同编号" v-if="!isSign">
                <el-input v-model="creatPro.contractCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">

              <!-- 项目名称 -->
              <el-form-item label="项目名称" prop="proName">
                <el-input v-model="creatPro.proName"></el-input>
              </el-form-item>
              <!-- pmp -->
              <!-- <el-form-item label="项目经理"  v-if="!isSign" prop="pmp"> -->
                <!-- 员工选择框子组件 -->
                <!-- <user-sel :users="users" @seluser="selUser" v-model="creatPro.pmp"></user-sel> -->
              <!-- </el-form-item> -->
               <el-form-item label="项目经理"  v-if="!isSign" prop="pmp">
                  <el-autocomplete
                    v-model="creatPro.pmp"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入姓名"
                    @select="handleSelect"
                    style="width:100%;"
                    clearable
                  >
                  <template slot-scope="{ item }">
                    <div class="selName">
                      <span>{{ item.compName }} - {{ item.deptName }}</span>
                      <span>{{ item.userName }}</span>
                      <span>[{{ item.userId }}]</span>
                    </div>
                  </template>
                </el-autocomplete>
                </el-form-item>
              <!-- 项目周期 -->
              <el-form-item label="项目周期" v-if="!isSign" prop="cycle">
                <el-date-picker
                  v-model="creatPro.cycle"
                  style="width:100%"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="!isSign">
              <!-- 总监 -->
              <el-form-item label="总监">
                <el-input-number :min="0" :max="365" v-model="creatPro.director" placeholder="预估人天"></el-input-number>
              </el-form-item>
              <!-- 经理 -->
              <el-form-item label="经理">
                <el-input-number :min="0" :max="365" v-model="creatPro.manager" placeholder="预估人天"></el-input-number>
              </el-form-item>
              <!-- 员工 -->
              <el-form-item label="员工">
                <el-input-number :min="0" :max="365" v-model="creatPro.employees" placeholder="预估人天"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider v-if="!isSign"></el-divider>
          <el-row :gutter="24" v-if="!isSign">
            <el-col :span="8">
              <el-form-item label="费用类型">
                <el-select style="width:100%" v-model="creatPro.costType">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="费用金额">
                <el-input placeholder="请输入金额" v-model="creatPro.amount" onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')">
                  <template slot="prepend">￥</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="费用周期">
                <el-date-picker
                  v-model="creatPro.costCycle"
                  style="width:100%"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 备注说明 输入长度限制20-->
          <el-form-item label="备注说明" prop="note">
            <el-input
              type="textarea"
              placeholder="备注说明（20字以内）"
              :rows="3"
              maxlength="20"
              v-model="creatPro.note"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="card-line">
          <!-- 立即修改 -->
          <el-button type="primary" size="small" @click="onSubmit" :disabled="isSubmit">立即申请</el-button>
          <!-- 重置 初始化表单数据 -->
          <el-button size="small" @click="reset" :disabled="isSubmit">清空</el-button>
          <!-- 返回 -->
          <el-button size="small" style="float:right" @click="goBack">返回</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入员工选择框子组件
import userSel from '@/components/UserSel/index.vue';

export default {
  // 注入组件
  components: {
    userSel
  },
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },
  // 当前实例数据
  data () {
    return {
      // 防止重复提交
      isSubmit: false,
      // 获取选中用户信息
      getUser: [],
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 立项信息表单
      creatPro: {
        // 标记转签
        sign: 0,
        // 接收转签
        receive: 0,
        // 关联项目
        related: '',
        // 关联公司
        compId: '',
        // 项目类型
        type: '',
        // 关联客户
        cusId: '',
        // 项目合同编号
        contractCode: '',
        // 项目名称
        proName: '',
        // 项目经理
        pmp: '',
        // 项目周期
        cycle: '',
        // 总监预估人天
        director: 0,
        // 经理预估人天
        manager: 0,
        // 员工预估人天
        employees: 0,
        // 费用类型
        costType: '',
        // 预算金额
        amount: '',
        // 费用周期
        costCycle: '',
        // 备注说明
        note: ''
      },

      // 是否关联项目
      isRelat: false,

      // 是否标记转签
      isSign: false,

      // 表单验证规则
      creatProRules: {
        compId: [{ required: true, message: '请选择归属公司', trigger: 'change' }],
        type: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
        cusId: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
        proName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        pmp: [{ required: true, message: '请选择项目经理', trigger: 'change' }],
        cycle: [{ required: true, message: '请选择项目周期', trigger: 'change' }]
      },

      // 所有公司数据
      compList: [],

      // 所有客户数据
      cusList: [],

      // 所有用户信息
      users: [],

      // 所有转签项目数据
      signList: [],

      options: [{
        value: 'XSE',
        label: '预计销售额'
      }],

      // 所有员工数据
      usersAll: [],

      // 模糊搜索
      restaurants: [],
      state: '',
      timeout: null
    };
  },

  // 创建实例后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 查询所有公司
    this.getCompList();

    // 查询所有客户
    this.getCusList();

    // 获取所有员工
    // this.getUserList();

    this.getUsersAll();

    // 获取所有转签项目
    this.getSignList();
  },

  mounted () {
    this.restaurants = this.loadAll();
  },

  methods: {

    // 获取所有员工数据
    getUsersAll () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          for (let i = datas.length; i--;) {
            _this.usersAll.push({
              compName: datas[i].compName,
              deptName: datas[i].deptName,
              userId: datas[i].userId,
              userName: datas[i].userName
            });
          };
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 加载全部员工数据
    loadAll () {
      return this.usersAll;
    },

    // 自动检索匹配
    querySearchAsync (queryString, cb) {
      let _this = this;
      let restaurants = _this.restaurants;
      let results = queryString ? restaurants.filter(_this.createStateFilter(queryString)) : restaurants;
      clearTimeout(_this.timeout);
      _this.timeout = setTimeout(() => {
        cb(results);
      }, 300 * Math.random());
    },

    // 查询
    createStateFilter (queryString) {
      return (state) => {
        return (state.userName.indexOf(queryString) === 0);
      };
    },

    // 选中赋值
    handleSelect (item) {
      this.creatPro.pmp = item.userName + ' [' + item.userId + ']';
    },

    // 获取选中用户信息
    selUser (data) {
      this.getUser = data;
      this.creatPro.pmp = data[0];
    },

    // 获取所有用户
    getUserList () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.users = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询所有公司
    getCompList () {
      this.$http.post('/api/findAllCompNoPage').then(res => {
        let {code, datas} = res;
        if (code === 0) {
          this.compList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询所有客户
    getCusList () {
      this.$http.post('/api/findAllCus').then(res => {
        let {code, datas} = res;
        if (code === 0) {
          this.cusList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询所有转签项目
    getSignList () {
      this.$http.post('/api/findAllSignPro').then(res => {
        let {code, datas} = res;
        if (code === 0) {
          this.signList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 返回
    goBack () {
      this.$router.push({ path: '/home/prolist' });
    },

    // 是否接收转签
    isRelated () {
      if (this.creatPro.receive === 1) {
        this.isRelat = true;
        this.$refs['creatPro'].resetFields();
      } else {
        this.isRelat = false;
        this.$refs['creatPro'].resetFields();
      }
    },

    // 是否标记转签
    isSigned () {
      if (this.creatPro.sign === 1) {
        this.isSign = true;
        this.$refs['creatPro'].resetFields();
        this.creatProRules = {
          compId: [{ required: true, message: '请选择归属公司', trigger: 'change' }],
          type: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
          cusId: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
          proName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }]
        };
      } else {
        this.isSign = false;
        this.$refs['creatPro'].resetFields();
        this.creatProRules = {
          compId: [{ required: true, message: '请选择归属公司', trigger: 'change' }],
          type: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
          cusId: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
          proName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
          pmp: [{ required: true, message: '请选择项目经理', trigger: 'change' }],
          cycle: [{ required: true, message: '请选择项目周期', trigger: 'change' }]
        };
      }
    },
    // 提交立项
    onSubmit () {
      let _this = this;
      let userId = _this.creatPro.pmp;
      if (userId.indexOf('[') && userId.indexOf(']')) {
        userId = userId.slice(userId.indexOf('[') + 1, userId.indexOf(']'));
      }
      // 收集请求数据
      let params = {
        // 标记转签
        sign: _this.creatPro.sign,
        // 接收转签
        receive: _this.creatPro.receive,
        // 关联项目
        related: _this.creatPro.related,
        // 关联公司
        compId: _this.creatPro.compId,
        // 项目类型
        type: _this.creatPro.type,
        // 关联客户
        cusId: _this.creatPro.cusId,
        // 项目合同编号
        contractCode: _this.creatPro.contractCode,
        // 项目名称
        proName: _this.creatPro.proName,
        // 项目经理
        pmp: userId,
        // 项目周期 - 开始时间
        cycleStart: _this.creatPro.cycle[0],
        // 项目周期 - 结束时间
        cycleEnd: _this.creatPro.cycle[1],
        // 总监预估人天
        director: _this.creatPro.director,
        // 经理预估人天
        manager: _this.creatPro.manager,
        // 员工预估人天
        employees: _this.creatPro.employees,
        // 费用类型
        costType: _this.creatPro.costType,
        // 预算金额
        amount: _this.creatPro.amount,
        // 费用周期 - 开始时间
        costCycleStart: _this.creatPro.costCycle[0],
        // 费用周期 - 结束时间
        costCycleEnd: _this.creatPro.costCycle[1],
        // 备注说明
        note: _this.creatPro.note
      };

      // 防止重复提交
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);
      this.$nextTick(() => {
        // 判断是否通过验证规则验证
        this.$refs['creatPro'].validate(valid => {
          if (valid) {
            // 添加项目
            this.$http.raw('api/insertPro', params).then(res => {
              let { code } = res;
              // 判断Code状态
              if (code === 0) {
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                // 初始化弹窗表单数据
                this.$refs['creatPro'].resetFields();
                this.goBack();
              }
            }).catch(err => {
              if (err === undefined) {
                this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    },
    // 清空立项
    reset () {
      this.$refs['creatPro'].resetFields();
    },
    // 按钮级授权
    authorization (data) {
      for (let i in data) {
        if (data['sel'] === 0) {
          this.btnSel = false;
        }
        if (data['add'] === 0) {
          this.btnAdd = false;
        }
        if (data['del'] === 0) {
          this.btnDel = false;
        }
        if (data['upload'] === 0) {
          this.btnUpload = false;
        }
        if (data['down'] === 0) {
          this.btnDown = false;
        }
        if (data['edit'] === 0) {
          this.btnEdit = false;
        }
        return i;
      }
    },
    handleClick (tab, event) {
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
